package com.ccit.order.api;

import com.ccit.common.client.AreaClient;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.PageUtil;
import com.ccit.model.Order;
import com.ccit.model.vo.order.OrderVo;
import com.ccit.order.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "柜台入场订单Mongodb")
@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private AreaClient areaClientService;

    //上传订单接口
    /*@PostMapping("saveOrder/{num}")
    public Result saveOrder(@RequestBody Order order) {
        orderService.saveOrder(order);
        return Result.ok();
    }*/

    //根据id查订单
    @GetMapping("/findOrderById/{id}")
    public Result findOrderById(@PathVariable Long id) {
        Order order = orderService.findOrderById(id);
        return Result.ok(order);
    }

    //根据手机号查询订单
    @GetMapping("/findOrderByPhone/{phone}")
    public Result findOrderByPhone(@PathVariable String phone) {
        List<Order> orderByPhone = orderService.findOrderByPhone(phone);
        return Result.ok(orderByPhone);
    }

    //根据id删除订单
    @DeleteMapping("/deleteOrderById/{id}")
    public Result deleteOrderById(@PathVariable Long id) {
        orderService.deleteOrderById(id);
        return Result.ok();
    }

    //修改订单
    @PutMapping("/updateOrder")
    public Result updateOrder(@RequestBody Order order) {
        orderService.saveOrder(order);
        return Result.ok();
    }

    //查询所有订单
    @GetMapping("/findAllOrder")
    public Result findAllOrder() {
        List<Order> orderList = orderService.findAllOrder();
        return Result.ok(orderList);
    }

    //条件查询订单
    @GetMapping("/findOrderList")
    public Result findOrderList(@RequestBody Order order) {
        List<Order> orderList = orderService.findOrderList(order);
        return Result.ok(orderList);
    }

    //模糊查询订单
    @GetMapping("/findOrderLike")
    public Result findOrderLike(@RequestBody Order order) {
        List<Order> orderList = orderService.findOrderLike(order);
        return Result.ok(orderList);
    }

    //分页查询订单
    @GetMapping("/findOrderPage/{currPage}/{pageSize}")
    public Result findOrderPage(@PathVariable Integer currPage, @PathVariable Integer pageSize, @RequestBody Order order) {
        Page<Order> orderPage = orderService.findOrderPage(currPage, pageSize, order);
        return Result.ok(orderPage);
    }

    //历史订单查询
    @GetMapping("/findAllOrder/{current}/{limit}")
    public Result findOrder(@PathVariable("current") Integer current,
                            @PathVariable("limit") Integer limit) {
        List<Order> orderList = orderService.findAllOrder();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page pages = PageUtil.getPages(current, limit, orderList);
        return Result.ok(pages);
    }

    //查询5年之前订单
    @GetMapping("/getYear")
    public Result getYear() {
        String[] split = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString().split("-");

        ArrayList<OrderVo> orderVos = new ArrayList<>();
        for (int i = Integer.valueOf(split[0]) + 1; i > Integer.valueOf(split[0]) - 5; i--) {
            OrderVo orderVo = new OrderVo();
            orderVo.setDate(Integer.toString(i - 1) + "年");
            try {
                Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(i - 1 + "-00-00");
                Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(i + "-00-00");

                List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                if (orderList != null) {
                    orderVo.setCount(orderList.size());
                } else orderVo.setCount(0);
                orderVos.add(orderVo);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return Result.ok(orderVos);
    }

    //"查询过去半年每月订单"
    @GetMapping("/getMonth")
    public Result getMonth() {
        String[] split = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString().split("-");

        ArrayList<OrderVo> orderVos = new ArrayList<>();

        if (Integer.valueOf(split[1]) - 6 >= 0) {
            for (int i = Integer.valueOf(split[1]) + 1; i > Integer.valueOf(split[1]) - 5; i--) {
                OrderVo orderVo = new OrderVo();
                orderVo.setDate(split[0] + "年" + Integer.toString(i - 1) + "月");

                try {
                    Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + (i - 1) + "-00");
                    Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + i + "-00");

                    List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                    if (orderList != null) {
                        orderVo.setCount(orderList.size());
                    } else orderVo.setCount(0);
                    orderVos.add(orderVo);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        } else {
            for (int i = Integer.valueOf(split[1]) + 1; i > 0; i--) {
                OrderVo orderVo = new OrderVo();
                orderVo.setDate(split[0] + "年" + Integer.toString(i - 1) + "月");

                try {
                    Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + (i - 1) + "-00");
                    Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + i + "-00");

                    List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                    if (orderList != null) {
                        orderVo.setCount(orderList.size());
                    } else orderVo.setCount(0);
                    orderVos.add(orderVo);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 12; i >= 12 + Integer.valueOf(split[1]) - 5; i--) {
                OrderVo orderVo = new OrderVo();
                orderVo.setDate(Integer.valueOf(split[0]) - 1 + "年" + Integer.toString(i - 1) + "月");

                try {
                    Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) - 1 + "-" + (i - 1) + "-00");
                    Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) - 1 + "-" + i + "-00");

                    List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                    if (orderList != null) {
                        orderVo.setCount(orderList.size());
                    } else orderVo.setCount(0);
                    orderVos.add(orderVo);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok(orderVos);
    }


    //查询过去时间(默认今年)订单场地占比
    @GetMapping("/getAreaRate")
    public Result getAreaRate(@RequestParam(required = false) Integer year,@RequestParam(required = false) Integer month){
        String[] split = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString().split("-");
        if (year != null){
            split[0] = Integer.toString(year);
        }
        if (month != null){
            split[1] = Integer.toString(month);
        }
        try {
            Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(split[0] + "-00-00");
            Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(split[0] +"-"+ Integer.valueOf(split[1])+1  +"-00");

            List<Order> list = orderService.findOrderByTime(startTime, endTime);
            Map<String,List<Order>> orderMaps = new HashMap<>();
            list.forEach(order -> {
                List<Order> orderList=new ArrayList<>();
                if (orderMaps.get(order.getArea())!=null){
                    orderList = orderMaps.get(order.getArea());
                }
                orderList.add(order);
                orderMaps.put(order.getArea(),orderList);
            });
            List<OrderVo> orderVoList = new ArrayList<>();
            orderMaps.forEach((s, orders) -> {
                OrderVo orderVo = new OrderVo();
                orderVo.setDate(split[0]+"-"+split[1]);
                orderVo.setArea(s);
                orderVo.setAreaRate((double)orders.size()/list.size());
                /*orderVo.setOrderList(orders);*/
                orderVoList.add(orderVo);
            });
            Map<String,Integer> ordersMaps = new HashMap<>();
            orderMaps.forEach((s, orders) -> {
                ordersMaps.put(s,orders.size());
            });
            return Result.ok(orderVoList);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Result.fail();
    }

    //根据手机号查询订单(分页)
    @GetMapping("/getByPage/{current}/{size}/{phone}")
    public Result selectOrderByPhone(@PathVariable("current") Integer current,
                                     @PathVariable("size") Integer size,
                                     @PathVariable("phone") String phone){
//        Order order = new Order();
//        order.setPhone(phone);
        List<Order> orderByPhone = orderService.findOrderByPhone(phone);
        if (orderByPhone==null){
            throw new GymException(202,"无此手机用户");
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page pages = PageUtil.getPages(current, size, orderByPhone);
//        Page<Order> page = orderService.findOrderPage(current, size, order);

        return Result.ok(pages);
    }


  @ApiOperation(value = "添加新订单")
    @PostMapping("/saveOrder/{num}")
    public Result saveOrder(@RequestBody Order order, @PathVariable Integer num) {
//        redisUtils.deleteRedisKeys("orderListByPage");


        boolean flag = areaClientService.updateAreaPersonNumByName(order.getArea(), num);
        if (flag){
            orderService.saveNewOrder(order, num);
//            orderService.saveOrder(order);
            return Result.ok();
        }
        else
            return Result.fail().message("更新区域人数出错啦!");
    }

    //mysql转mongodb
    @GetMapping("/get")
    public Result selectOrderMysql(){
        List<Order> list = orderService.list();
        list.forEach(order -> {
            orderService.saveOrder(order);
        });
        List<Order> allOrder = orderService.findAllOrder();
        return Result.ok(allOrder);
    }
}